﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using smsgs_MVC3.Utils;
using smsgs_MVC3.Areas.Messages.Models;

namespace smsgs_MVC3.Areas.Messages.Controllers
{
    public partial class MsgController : Controller
    {
        //
        // GET: /Messages/Msg/
        [Authorize]
        public virtual ActionResult Index(int? pageID)
        {
            var u = SiteUtils.UserLoggedOn;
            if (u == null)
            {
                return RedirectToAction("Logon", "Account", new {Area="" });
            }
            MessagesView mv = new MessagesView(u);
            //TODO : order by date
            //TODO : page size from web.config
            mv.Load(pageID ?? 1, 10, null);
            return View(mv);
        }

        [Authorize]
        public virtual ActionResult ViewMessage(long id)
        {
            var u = SiteUtils.UserLoggedOn;
            if (u == null)
            {
                return RedirectToAction("Logon", "Account", new { Area = "", returnUrl = Url.Action(MVC.Messages.Msg.ViewMessage(id)) });
            }
            MessageView mv = new MessageView(u);
            
            mv.Load(id);
            
            return View(mv) ;
        }
        [Authorize]
        public virtual ActionResult CreateNewMessage(long? id)
        {
            var u = SiteUtils.UserLoggedOn;
            if (u == null)
            {
                return RedirectToAction("Logon", "Account", new { Area = "" });
            }
            MessageViewNew mv = new MessageViewNew(u);

            mv.LoadPreviousMessage(id);
            mv.LoadFriends();
            return View( mv);
        }
        [Authorize]
        [HttpPost]
        public virtual ActionResult CreateNewMessage(long? id, FormCollection fc)
        {

            var u = SiteUtils.UserLoggedOn;
            if (u == null)
            {
                return RedirectToAction("Logon", "Account", new { Area = "", returnUrl = Url.Action(MVC.Messages.Msg.CreateNewMessage(id))});
            }
            MessageViewNew mv = new MessageViewNew(u);
            UpdateModel(mv.NewMessage, "NewMessage",new string[]{"ToUser","Subject", "Body"});

            mv.LoadPreviousMessage(id);
            mv.Save();
            
            return Content(mv.NewMessage.To.Key);


        }
    }
}
